package com.vlyman.redis.utils;

import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * 类描述：
 *  序列化工具
 * @author chenjs
 * @date 2019/1/14 19:29
 **/
@Slf4j
public class SerializableUtil {

    /**
     * 方法描述：
     *   序列化
     *  @author chenjs
     *  @param object 待序列化对象
     *  @return byte[]
     *  @date 2019/1/14 23:09
     */
    public static byte[] serializable(Object object) throws Exception{
        @Cleanup
        ByteArrayOutputStream baos = null;
        @Cleanup
        ObjectOutputStream oos = null;
        try {
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            byte[] bytes = baos.toByteArray();
            return bytes;
        } catch (Exception e) {
            log.error("SerializableUtil工具类序列化出错:" + e.getMessage());
            throw new Exception("SerializableUtil工具类序列化出错:" + e.getMessage());
        }
    }

    /**
     * 方法描述：
     *   反序列化
     *  @author chenjs
     *  @param bytes 待反序列化字节组
     *  @return 反序列化得出对象
     *  @date 2019/1/14 23:14
     */
    public static Object unserializable(byte[] bytes) throws Exception{
        @Cleanup
        ByteArrayInputStream bais = null;
        @Cleanup
        ObjectInputStream ois = null;
        try {
            bais = new ByteArrayInputStream(bytes);
            ois = new ObjectInputStream(bais);
            return ois.readObject();
        } catch (Exception e) {
            log.error("SerializableUtil工具类反序列化出错:" + e.getMessage());
            throw new Exception("SerializableUtil工具类反序列化出错:" + e.getMessage());
        }
    }
}
